import cv2
import json
import base64
import requests
import os
import sys
import errno
from pathlib import Path

# 将图片转换为Base64字符串
def mat_to_base64(img):
    _, buf = cv2.imencode(".png", img)
    return base64.b64encode(buf).decode('utf-8')

# 发起POST请求的函数
def post_request(url, data):
    try:
        response = requests.post(url, json=data)
        response.raise_for_status()  # 检查HTTP错误
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"Error during API request: {e}")
        raise

# 处理返回的JSON
def handle_response(response):
    if "code" in response:
        code = response["code"]
        if code == 200:
            print("Success: Code 200")
        elif code == 201:
            print("Success: Code 201")
        else:
            print(f"Unknown code: {code}")
    else:
        print("Response does not contain 'code' field")

# 解析JSON并裁切图片
def process_subjects(json_path, image_path, output_dir):
    # 读取JSON文件
    with open(json_path, 'r') as f:
        body_data = json.load(f)

    resp = {"json_list": []}
    json_list = []

    # 创建输出目录
    Path(output_dir).mkdir(parents=True, exist_ok=True)

    # 加载原始图片
    img = cv2.imread(image_path)
    if img is None:
        print(f"Error loading image: {image_path}")
        return resp

    # 遍历所有题目
    subject_count = 0
    for page in body_data["pages"]:
        for subject in page["subjects"]:
            for content in subject["content_list_info"]:
                # 提取坐标点
                points = []
                for p in content["pos"]:
                    points.append({"x": p["x"], "y": p["y"]})

                # 计算裁切区域
                if len(points) != 4:
                    print(f"Invalid points count: {len(points)}")
                    continue

                # 找到边界坐标
                x_min = min(p["x"] for p in points)
                x_max = max(p["x"] for p in points)
                y_min = min(p["y"] for p in points)
                y_max = max(p["y"] for p in points)

                # 边界检查
                x_min = max(0, x_min)
                x_max = min(img.shape[1] - 1, x_max)
                y_min = max(0, y_min)
                y_max = min(img.shape[0] - 1, y_max)

                # 执行裁切
                if x_max > x_min and y_max > y_min:
                    sub_img = img[y_min:y_max, x_min:x_max]

                    # 保存结果
                    subject_count += 1
                    output_path = os.path.join(output_dir, f"subject_{subject_count}.png")
                    cv2.imwrite(output_path, sub_img)

                    # 将图片转换为Base64
                    base64_img = mat_to_base64(sub_img)
                    request_data = {
                        "content": subject["text"],
                        "picture": base64_img
                    }
                    print(subject["text"])
                    print(request_data["content"])

                    # 向API发送请求，检查是否有这道题
                    try:
                        response = post_request("http://112.124.43.86:3000/api/question/addQuestionWithPic", request_data)
                        json_list.append(response)
                        handle_response(response)
                    except Exception as e:
                        print(f"Error during API request: {e}")

    resp["json_list"] = json_list
    print(f"Processed {subject_count} subjects")
    return resp

if __name__ == "__main__":
    if len(sys.argv) != 5:
        print(f"Usage: {sys.argv[0]} <input.json> <input_image> <output_dir> <output_json>")
        sys.exit(1)

    json_path = sys.argv[1]
    image_path = sys.argv[2]
    output_dir = sys.argv[3]
    output_json = sys.argv[4]

    try:
        resp = process_subjects(json_path, image_path, output_dir)
        with open(output_json, 'w') as f:
            json.dump(resp, f, indent=4)
        print(f"JSON data has been saved to {output_json}")
    except Exception as e:
        print(f"Error: {e}")
        sys.exit(1)
